#!/usr/bin/env node
// 告诉操作系统用 node 去执行脚本
import { program } from "commander"
import inquirer from "inquirer"
import ora from "ora"
// 因为inquirer这个库内部只支持esmoudle导出，所以项目package.json里面配置了type: "module"
// 而node里面的所有导出前面加node:
import fs from "node:fs"
import {
  checkPath,
  compileEjs,
  downloadTemp,
  execCommand,
  helpOptions,
} from "./utils.js"

// 配置options
helpOptions()

// 下载模板并安装依赖
program
  .command("create <projectName>")
  .alias("c")
  .description("创建项目,比如：gk-cli create xxx")
  .action((projectName) => {
    inquirer
      .prompt([
        {
          type: "input",
          name: "projectName", // 返回值的key
          message: "请输入项目名称", // 描述
          default: projectName, //默认值
        },
        {
          type: "confirm",
          name: "isTs",
          message: "是否选用typescript",
        },
      ])
      .then(async (res) => {
        if (checkPath(res.projectName)) {
          console.log("文件夹已经存在")
          return
        }
        // 1.下载模板
        await downloadTemp(res.isTs, res.projectName)
        const spinner = ora("正在安装依赖...")
        // 2.执行npm install, {cwd: `./${res.porjectName}`去哪个文件夹执行命令
        // 不同系统使用的npm命名不一样
        const commandName = process.platform === "win32" ? "npm.cmd" : "npm"
        await execCommand(commandName, ["install"], {
          cwd: `./${res.projectName}`,
        })
        spinner.succeed("依赖安装完成")
        // 3.执行npm run dev
        await execCommand(commandName, ["run", "dev"], {
          cwd: `./${res.projectName}`,
        })
      })
  })

// 添加组件
program
  .command("addcpn <cpnName> [...others]")
  .alias("cpn")
  .description("创建组件,比如：gk-cli addcpn good-item -d src/components")
  .action(async (name) => {
    // 选择框
    const result = await inquirer.prompt([
      {
        type: "list",
        name: "isTs",
        message: "请选择组件类型",
        choices: [
          {
            name: "typescript",
            value: true,
          },
          {
            name: "javascript",
            value: false,
          },
        ],
        default: true,
      },
    ])

    // 获取ejs模板
    let content
    if (result.isTs) {
      content = await compileEjs("component-ts.vue.ejs", name)
    } else {
      content = await compileEjs("component-js.vue.ejs", name)
    }

    let dest
    if (program.opts().dest) {
      dest = program.opts().dest + `/${name}`
    } else {
      dest = `src/components/${name}`
    }

    // 如果不存在，创建文件夹
    if (!fs.existsSync(dest)) {
      fs.mkdirSync(dest, { recursive: true })
    }

    // 将ejs内容写入vue文件
    await fs.promises.writeFile(`${dest}/${name}.vue`, content)
    console.log("创建组件成功", name + ".vue")
  })

// 解析参数
program.parse(process.argv)
